//
//  WaterCameraView.m
//  yuanduo_app
//
//  Created by ZekiMini on 2021/7/28.
//

#import "WaterCameraView.h"
#import <GPUImage.h>
#import "GPUImage.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "SLShotFocusView.h"
#import "WaterCameraQRCodeView.h"
#import "UIView+GJImage.h"
#import <Photos/Photos.h>
@interface WaterCameraView ()<GPUImageVideoCameraDelegate, MAMapViewDelegate>

@property (nonatomic, strong) UIImageView *photoBackView; //拍完照片显示的View

@property (nonatomic, strong) GPUImageStillCamera* videoCamera; //相机
@property (nonatomic, strong) GPUImageView *captureView; //预览视图
@property (nonatomic, strong) GPUImageFilter *filter; //原图像
@property (nonatomic, strong) UIView *bottomView; // 底部视图
@property (nonatomic, strong) UIButton *shotButton; //拍摄按钮
@property (nonatomic, strong) UIButton *bottomHistory; // 历史按钮
@property (nonatomic, strong) UIButton *bottomCancel; //退出按钮

@property (nonatomic, strong) UITextField *licensePlate; //车牌号

@property (nonatomic, strong) MAMapView *mapView; // 地图
@property (nonatomic, strong) UIImageView *mapSnapView; //
@property (nonatomic, strong) UIButton *rollingButton; //反转按钮
@property (nonatomic, strong) UIButton *lightButton; //闪光灯按钮
@property (nonatomic, strong) UILabel *timeLabel; //时间
@property (nonatomic, strong) UILabel *dateLabel; //日期
@property (nonatomic, strong) UILabel *addressLabel; //地址
@property (nonatomic, strong) UIImageView *dateIcon; //日期图标
@property (nonatomic, strong) UIImageView *addressIcon; //地址图标
@property (nonatomic, strong) UIImageView *distanceIcon; //距离图标
@property (nonatomic, strong) UILabel *distanceLabel; //距离

@property (nonatomic, strong) UIButton *mapIconButton; //地图图标
@property (nonatomic, strong) UIButton *closeMapButton; //关闭地图
@property (nonatomic, strong) UIButton *reduiceButton; //缩小
@property (nonatomic, strong) UIButton *addButton; //放大

@property (nonatomic, strong) SLShotFocusView *focusView;   //当前聚焦视图
@property (nonatomic, assign) CGFloat currentZoomFactor; //当前焦距比例系数

@property (nonatomic, assign) UIDeviceOrientation shootingOrientation;// 拍摄时的设备方向 开始录制时停止更新

@property (nonatomic, assign) CGFloat currentZoomLevel; //当前缩放等级

//@property (nonatomic, strong) WaterCameraQRCodeView *qrCodeView; //底部二维码视图

@property (nonatomic, assign) BOOL isShowMap; //是否显示地图
@property (nonatomic, assign) BOOL isShowDistance; // 是否显示距离
@property (nonatomic, strong) UIImage *takePhotoImage; //拍完照片的图片

@property (nonatomic, strong) NSString *gcdTimerName; //定时器
@property (nonatomic, strong) NSDictionary *addressDic; //位置信息
@end

#define kBottomViewHeight 121
#define kShotBtnWidth 72
#define PHOTOCACHEPATH [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject]
@implementation WaterCameraView

- (instancetype)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if (self) {
    [self initlizationSubViews];
    [self initlizationCameraView];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      [self.videoCamera startCameraCapture];
    });
  }
  return self;
}

#pragma mark - initlization
- (void)initlizationSubViews{
  
  [self addSubview:self.photoBackView];
  [self.photoBackView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(self);
  }];
  
  
  self.isShowDistance = NO;
  self.isShowMap = YES;
  self.backgroundColor = [UIColor whiteColor];
  self.userInteractionEnabled = YES;
  [self addSubview:self.bottomView];
  [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.width.equalTo(self);
    make.height.mas_equalTo(kBottomViewHeight);
    make.bottom.equalTo(self);
  }];
  [self.bottomView addSubview:self.bottomHistory];
  [self.bottomView addSubview:self.shotButton];
  [self.bottomView addSubview: self.bottomCancel];
  [self.bottomCancel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.right.equalTo(self.bottomView);
    make.width.mas_equalTo((kScreenWidth - kShotBtnWidth)*0.5);
    make.height.mas_equalTo(44);
    make.centerY.equalTo(self.shotButton);
  }];
  [self.bottomHistory mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.bottomView);
    make.width.mas_equalTo((kScreenWidth - kShotBtnWidth)*0.5);
    make.height.mas_equalTo(44);
    make.centerY.equalTo(self.shotButton);
  }];
  [self.shotButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.width.height.mas_equalTo(kShotBtnWidth);
    make.centerX.equalTo(self.bottomView);
    make.top.equalTo(self.bottomView).offset(13);
  }];
  
  [self.photoBackView addSubview:self.licensePlate];
  [self addSubview:self.mapView];
  
  [self addSubview:self.rollingButton];
  [self addSubview:self.lightButton];
  
  [self.photoBackView addSubview:self.timeLabel];
  [self.photoBackView addSubview:self.addressLabel];
  [self.photoBackView addSubview:self.addressIcon];
  [self.photoBackView addSubview:self.dateLabel];
  [self.photoBackView addSubview:self.dateIcon];
  [self.photoBackView addSubview:self.distanceLabel];
  [self.photoBackView addSubview:self.distanceIcon];
  self.distanceIcon.hidden = self.distanceLabel.hidden = YES;
  [self.distanceIcon mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.licensePlate);
    make.height.width.mas_equalTo(24);
    make.bottom.equalTo(self.bottomView.mas_top).offset(-28);
  }];
  [self.distanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.height.equalTo(self.distanceIcon);
    make.right.equalTo(self).offset(-12);
    make.left.equalTo(self.distanceIcon.mas_right).offset(8);
  }];
  [self.addressIcon mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.licensePlate);
    make.height.width.mas_equalTo(24);
    make.bottom.equalTo(self.bottomView.mas_top).offset(-16);
  }];
  [self.addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.height.equalTo(self.addressIcon);
    make.right.equalTo(self).offset(-12);
    make.left.equalTo(self.addressIcon.mas_right).offset(8);
  }];
  
  [self.dateIcon mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.height.equalTo(self.addressIcon);
    make.bottom.equalTo(self.addressIcon.mas_top).offset(-4);
  }];
  
  
  [self.dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.height.equalTo(self.dateIcon);
    make.width.mas_equalTo(120);
    make.left.equalTo(self.addressLabel);
  }];
  [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.height.equalTo(self.dateIcon);
    make.left.equalTo(self.dateLabel.mas_right).offset(5);
    make.right.equalTo(self.addressLabel);
  }];
  [self.licensePlate mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(13);
    make.height.mas_equalTo(31);
    make.width.mas_equalTo(120);
    make.bottom.equalTo(self.dateIcon.mas_top).offset(-12);
  }];
  // 显示时间地址
  [self addressAndTime];
  
  [self addSubview:self.addButton];
  [self addSubview:self.closeMapButton];
  [self addSubview:self.reduiceButton];
  [self addSubview: self.mapIconButton];
  [self.mapIconButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.right.equalTo(self.mapView);
    make.height.width.mas_equalTo(40);
  }];
  [self.closeMapButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.mapView.mas_right);
    make.height.width.mas_equalTo(24);
    make.top.equalTo(self.mapView.mas_top);
  }];
  
  [self.reduiceButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.equalTo(self.mapView);
    make.width.height.mas_equalTo(24);
    make.left.equalTo(self.mapView.mas_right);
  }];
  [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.height.equalTo(self.reduiceButton);
    make.bottom.equalTo(self.reduiceButton.mas_top).offset(-12);
  }];
  
  self.mapIconButton.hidden = YES;
  [self.photoBackView addSubview:self.mapSnapView];
//  self.mapSnapView.hidden = YES;
}

- (void)initlizationCameraView{
  [self.filter addTarget:self.captureView];
  [self.videoCamera addTarget:self.filter];
//  [self.videoCamera startCameraCapture];
  [self insertSubview:self.captureView atIndex:0];
}

#pragma mark -- bridges
- (void)tapChangeLicensePlate:(UITapGestureRecognizer *)gesture{
  [GJUtil sendNotificationForRNEventEmitterWithActionKey:@"License_Plate" parameter:@{@"":@""}];
}

#pragma mark - handleEvent

- (void)changeBottomViewButtonTitle:(BOOL)isTakePicture{
  if (isTakePicture) {
    [self.bottomHistory setTitle:@"重拍" forState:UIControlStateNormal];
    [self.bottomCancel setTitle:@"使用照片" forState:UIControlStateNormal];
    self.shotButton.hidden = YES;
  }else{
    [self.bottomHistory setTitle:@"历史" forState:UIControlStateNormal];
    [self.bottomCancel setTitle:@"退出" forState:UIControlStateNormal];
    self.shotButton.hidden = NO;
  }
}
//TODO: 底部按钮
- (void)bottomHistoryClick:(UIButton *)sender{
  // 历史
  if ([sender.titleLabel.text isEqualToString:@"历史"]) {
    [GJUtil sendNotificationForRNEventEmitterWithActionKey:@"waterHistory" parameter:@{@"":@""}];
  }else{
    self.photoBackView.image = nil;
    self.takePhotoImage = nil;
    if (self.isShowMap) {
      self.mapView.showsUserLocation = YES;
      self.mapIconButton.hidden = YES;
      self.mapView.hidden = NO;
    }else{
      self.mapIconButton.hidden = NO;
    }
    self.rollingButton.hidden = NO;
    self.lightButton.hidden = NO;
    [self.videoCamera startCameraCapture];
    [GJGCDTimer resumeTimer:self.gcdTimerName];
    [self changeBottomViewButtonTitle:NO];
  }
}
- (void)bottomCancelClick:(UIButton *)sender{
  if ([sender.titleLabel.text isEqualToString:@"退出"]) {
    [GJUtil sendNotificationForRNEventEmitterWithActionKey:@"waterFinish" parameter:@{@"":@""}];
  }else{
    // 合成照片
    //  // 隐藏不需要的
      if (self.isShowMap) {
        self.mapView.showsUserLocation = NO;
        self.mapSnapView.image = [self.mapView takeSnapshotInRect:self.mapView.bounds];
        self.mapSnapView.hidden = NO;
      }else{
        self.mapSnapView.hidden = YES;
        self.mapIconButton.hidden = YES;
      }
    self.photoBackView.image = self.takePhotoImage;
    UIImage *saveImage = [self.photoBackView gj_imageByViewInRect:self.photoBackView.bounds];
    saveImage = [GJUtil compressImage:saveImage toByte:6110000];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        
    NSTimeInterval a=[dat timeIntervalSince1970];
    
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    
    
    NSString *filePath = [NSString stringWithFormat:@"/waterPhotos/%@%@",timeString,@".jpeg"];
    NSString *fullPath = [PHOTOCACHEPATH stringByAppendingString:filePath];
    NSData *data = UIImageJPEGRepresentation(saveImage, 1.f);
    if ([self saveImage:data toCachePath:fullPath]) {
      //保存相册
      [self saveImageIntoAlbum:saveImage];
      // 回调RN
      [GJUtil sendNotificationForRNEventEmitterWithActionKey:@"USER_WATER_CAMERA" parameter:@{
        @"filePath":fullPath,
        @"time":[NSString stringWithFormat:@"%@ %@",self.dateLabel.text, self.timeLabel.text],
        @"address":self.addressLabel.text?self.addressLabel.text:@"" ,
        @"lat":self.addressDic[@"latitude"] ?self.addressDic[@"latitude"]: @"" ,
        @"lng":self.addressDic[@"longitude"]?self.addressDic[@"latitude"] : @"",
        @"imageId": timeString,
      }];
    }

  }
}


//保存图片到相册
-(void)saveImageIntoAlbum:(UIImage *)image
{
  PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
  [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
      dispatch_async(dispatch_get_main_queue(), ^{
          switch (status) {
              case PHAuthorizationStatusAuthorized: {
                  //  保存图片到相册
                  
                UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
                
               
                  break;
              }
              case PHAuthorizationStatusDenied: {
                  if (oldStatus == PHAuthorizationStatusNotDetermined) return;
              
                [UIAlertController showAlertInViewController:[UIApplication sharedApplication].keyWindow.rootViewController withTitle:@"请允许访问相册权限" message:@"我们将拍摄的水印照片存储到相册" cancelButtonTitle:@"取消" destructiveButtonTitle:@"同意" otherButtonTitles:nil tapBlock:^(UIAlertController * _Nonnull controller, UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
                  if (buttonIndex == 1) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                  }
                }];
                  break;
              }
              case PHAuthorizationStatusRestricted: {
                 
                  break;
              }
              default:
                  break;
          }
      });
  }];
  

}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
 
}
// 地图缩放
- (void)mapZoomWithbutton:(UIButton *)sender{
  switch (sender.tag) {
    case 100:
    {
      // 减
      [_mapView setZoomLevel:self.currentZoomLevel-1 animated:YES];
    }
      break;
    case 99:
    {
      //加
      [_mapView setZoomLevel:self.currentZoomLevel+1 animated:YES];
    }
      break;
      
    default:
      break;
  }
}
//隐藏
- (void)hideMapViewWithButton:(UIButton *)sender{
  switch (sender.tag) {
    case 101:
    {
      // 隐藏
      self.isShowMap = NO;
    }
      break;
    case 102:
    {
      // 显示
      self.isShowMap = YES;
    }
      break;
      
    default:
      break;
  }
}
// 获取位置和时间
- (void)addressAndTime{
  [[GJLocationUtil shareInstance] getLocationWithCommplete:^(CLLocationCoordinate2D coordinate, NSDictionary * _Nonnull addressDic, NSError * _Nonnull error) {
    [[GJLocationUtil shareInstance] stopSerialLocation];
    if (error == nil) {
      self.addressLabel.text = addressDic[@"addressDetail"];
      self.addressDic = addressDic;
    }else{
      if (![GJUtil hasLocationAuthorization]) {
        [UIAlertController showAlertInViewController:[UIApplication sharedApplication].keyWindow.rootViewController withTitle:@"请允许访问位置信息" message:@"我们将获取您的位置信息，用于展示你的当前地址" cancelButtonTitle:@"取消" destructiveButtonTitle:@"同意" otherButtonTitles:nil tapBlock:^(UIAlertController * _Nonnull controller, UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
          if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
          }
        }];
      }
    }
  }];
  
  self.gcdTimerName = [GJGCDTimer execTask:^{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    [formatter setDateFormat:@"YYYY年MM月dd日"];
    NSString * dateString = [formatter stringFromDate:datenow];
    NSLog(@"currentTimeString =  %@ -- %@",currentTimeString, dateString);
    dispatch_async(dispatch_get_main_queue(), ^{
      self.dateLabel.text = dateString;
      self.timeLabel.text = currentTimeString;
    
    });
  } start:0 interval:1 repeats:YES async:YES];
  
}

//聚焦手势
- (void)tapFocusing:(UITapGestureRecognizer *)tap {
  //如果没在运行，取消聚焦
  if(!self.videoCamera.captureSession.isRunning) {
    return;
  }
  CGPoint point = [tap locationInView:self.captureView];
  if(point.y > self.shotButton.frame.origin.y || point.y < self.rollingButton.frame.origin.y+ self.rollingButton.frame.size.height) {
    return;
  }
  [self focusAtPoint:point];
}
//设置焦点视图位置
- (void)focusAtPoint:(CGPoint)point {
  self.focusView.center = point;
  [self.focusView removeFromSuperview];
  [self addSubview:self.focusView];
  self.focusView.transform = CGAffineTransformMakeScale(1.3, 1.3);
  [UIView animateWithDuration:0.5 animations:^{
    self.focusView.transform = CGAffineTransformIdentity;
  }];
  NSError *error;
  if([self.videoCamera.inputCamera lockForConfiguration:&error]){
    //对焦模式和对焦点,设定前一定要判断该模式是否支持，如果支持就先设定位置，然后再设定模式，单独设定位置是没有用的。曝光设置跟这里一样的原理
    if([self.videoCamera.inputCamera isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]){
      [self.videoCamera.inputCamera setFocusPointOfInterest:point];
      [self.videoCamera.inputCamera setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
    }
    //曝光模式和曝光点
    if([self.videoCamera.inputCamera isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]){
      [self.videoCamera.inputCamera setExposurePointOfInterest:point];
      [self.videoCamera.inputCamera setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
    }
    //当你lockForConfiguration后，完成设置后记住一定要unlock
    [self.videoCamera.inputCamera unlockForConfiguration];
  }
  //    SL_WeakSelf;
  //    [SLDelayPerform sl_startDelayPerform:^{
  //        [weakSelf.focusView removeFromSuperview];
  //    } afterDelay:1.0];
  dispatch_after(1, dispatch_get_main_queue(), ^{
    [self.focusView removeFromSuperview];
  });
}

//调节焦距 手势
- (void)pinchFocalLength:(UIPinchGestureRecognizer *)pinch {
  if(pinch.state == UIGestureRecognizerStateBegan) {
    self.currentZoomFactor = self.videoCamera.inputCamera.videoZoomFactor;
  }
  if (pinch.state == UIGestureRecognizerStateChanged) {
    NSError *error;
    if([self.videoCamera.inputCamera lockForConfiguration:&error]){
      if (self.currentZoomFactor * pinch.scale >= [self minZoomFactor] && self.currentZoomFactor * pinch.scale <= [self maxZoomFactor]) {
        self.videoCamera.inputCamera.videoZoomFactor = self.currentZoomFactor * pinch.scale;
      }
      //当你lockForConfiguration后，完成设置后记住一定要unlock
      [self.videoCamera.inputCamera unlockForConfiguration];
    }
  }
}





//轻触拍照
- (void)takePicture {
  UIImageOrientation imageOrientation = UIImageOrientationUp;
  switch (self.shootingOrientation) {
    case UIDeviceOrientationLandscapeLeft:
      imageOrientation = UIImageOrientationLeft;
      break;
    case UIDeviceOrientationLandscapeRight:
      imageOrientation = UIImageOrientationRight;
      break;
    case UIDeviceOrientationPortraitUpsideDown:
      imageOrientation = UIImageOrientationDown;
      break;
    default:
      break;
  }
  __weak __typeof(self)weakSelf = self;
  
  // 添加二维码 视图
  [self.videoCamera capturePhotoAsJPEGProcessedUpToFilter:weakSelf.filter withOrientation:imageOrientation withCompletionHandler:^(NSData *processedJPEG, NSError *error) {
    if(error){
      NSLog(@"拍照失败");
      return;
    }
    NSLog(@"拍照结束");
    
    // 拍照的照片
    self.takePhotoImage = [UIImage imageWithData:processedJPEG];
    
    [weakSelf changeBottomViewButtonTitle:YES];
    [weakSelf.videoCamera stopCameraCapture];
    [GJGCDTimer pauseTask:weakSelf.gcdTimerName];
  }];
  
}








//切换前/后摄像头
- (void)switchCameraClicked:(UIButton *)sender {
    [self.videoCamera rotateCamera];
}
- (void)switchLightClicked:(UIButton *)sender{
  sender.selected = !sender.selected;
  if (sender.isSelected == YES) { //打开闪光灯
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    
    if ([captureDevice hasTorch]) {
      BOOL locked = [captureDevice lockForConfiguration:&error];
      if (locked) {
        captureDevice.torchMode = AVCaptureTorchModeOn;
        [captureDevice unlockForConfiguration];
      }
    }
  }else{//关闭闪光灯
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
      [device lockForConfiguration:nil];
      [device setTorchMode: AVCaptureTorchModeOff];
      [device unlockForConfiguration];
    }
  }
  
}


#pragma mark - HelpMethods

//将Image保存到缓存路径中
- (BOOL)saveImage:(NSData *)imageData toCachePath:(NSString *)fullPath {
  NSFileManager *fileManager = [NSFileManager defaultManager];
  if (![fileManager fileExistsAtPath:fullPath]) {
    [fileManager createDirectoryAtPath:[fullPath stringByDeletingLastPathComponent]
           withIntermediateDirectories:YES
                            attributes:nil
                                 error:nil];
  } else {
    if ([fileManager removeItemAtPath:fullPath error:nil]) {
      [fileManager createDirectoryAtPath:[fullPath stringByDeletingLastPathComponent]
             withIntermediateDirectories:YES
                              attributes:nil
                                   error:nil];
    }
    
  }
  NSError *error;
  //    if ([imageData writeToFile:fullPath options:0 error:&error]) {
  //
  //    }else{
  //      NSLog(@"writeToFile failed with error %@", error);
  //    }
  //  return NO;
  //  return [data writeToFile:fullPath atomically:YES];
  return [imageData writeToFile:fullPath atomically:YES];
}

-(void)viewBorderLineWithLineWidth:(CGFloat)lineWidth lineColor:(UIColor *)lineColor view:(UIView *)view {
  CAShapeLayer *border = [CAShapeLayer layer];
  border.strokeColor = lineColor.CGColor;
  //border.cornerRadius = 4.0;
  border.fillColor = nil;
  border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;
  border.frame = view.bounds;
  border.lineWidth = lineWidth;
  border.lineDashPattern = @[@(8), @(8)];
  [view.layer addSublayer:border];
}

//最小缩放值 焦距
- (CGFloat)minZoomFactor {
  CGFloat minZoomFactor = 1.0;
  if (@available(iOS 11.0, *)) {
    minZoomFactor = self.videoCamera.inputCamera.minAvailableVideoZoomFactor;
  }
  return minZoomFactor;
}
//最大缩放值 焦距
- (CGFloat)maxZoomFactor {
  CGFloat maxZoomFactor = self.videoCamera.inputCamera.activeFormat.videoMaxZoomFactor;
  if (@available(iOS 11.0, *)) {
    maxZoomFactor = self.videoCamera.inputCamera.maxAvailableVideoZoomFactor;
  }
  if (maxZoomFactor > 6) {
    maxZoomFactor = 6.0;
  }
  return maxZoomFactor;
}

#pragma mark - GPUImageVideoCameraDelegate 音视频实时输出代理
- (void)willOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer {
  
}
#pragma mark -- mapViewDelegate
- (void)mapView:(MAMapView *)mapView mapDidZoomByUser:(BOOL)wasUserAction{
  self.currentZoomLevel = mapView.zoomLevel;
}
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
  [[GJLocationUtil shareInstance] zoomMapViewToFitAnnotations:self.mapView animated:YES];
}
#pragma mark - Getter
- (UIImage *)takePhotoImage{
  if (!_takePhotoImage) {
    _takePhotoImage = [UIImage imageNamed:@""];
  }
  return  _takePhotoImage;
}
- (GPUImageStillCamera *)videoCamera {
  if (!_videoCamera) {
    _videoCamera = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPresetHigh cameraPosition:AVCaptureDevicePositionBack];
    //设置输出图像方向，可用于横屏推流。
    _videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
    //镜像策略，这里这样设置是最自然的。跟系统相机默认一样。
    _videoCamera.horizontallyMirrorRearFacingCamera = NO;
    _videoCamera.horizontallyMirrorFrontFacingCamera = YES;
    // 可防止允许声音通过的情况下,避免第一帧黑屏
    [_videoCamera addAudioInputsAndOutputs];
    _videoCamera.delegate = self;
  }
  return _videoCamera;
}
- (GPUImageView *)captureView {
  if (!_captureView) {
    _captureView = [[GPUImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kBottomViewHeight)];
    _captureView.backgroundColor = [UIColor blackColor];
    _captureView.fillMode = kGPUImageFillModePreserveAspectRatioAndFill;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapFocusing:)];
    [_captureView addGestureRecognizer:tap];
    UIPinchGestureRecognizer  *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchFocalLength:)];
    [_captureView addGestureRecognizer:pinch];
  }
  return _captureView;
}
- (GPUImageFilter *)filter {
  if (!_filter) {
    _filter = [[GPUImageFilter alloc] init];
  }
  return _filter;
}
- (UIView *)bottomView{
  if (!_bottomView) {
    _bottomView = [[UIView alloc]initWithFrame:CGRectZero];
    _bottomView.backgroundColor = [UIColor blackColor];
  }
  return _bottomView;
}
- (UIButton *)bottomHistory{
  if (!_bottomHistory) {
    _bottomHistory = [[UIButton alloc]initWithFrame:CGRectZero];
    [_bottomHistory setTitle:@"历史" forState:UIControlStateNormal];
    _bottomHistory.titleLabel.font = [UIFont systemFontOfSize:18];
    _bottomHistory.titleLabel.textColor = [UIColor whiteColor];
    [_bottomHistory addTarget:self action:@selector(bottomHistoryClick:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _bottomHistory;
}
- (UIButton *)bottomCancel{
  if (!_bottomCancel) {
    _bottomCancel = [[UIButton alloc]initWithFrame:CGRectZero];
    [_bottomCancel setTitle:@"退出" forState:UIControlStateNormal];
    _bottomCancel.titleLabel.font = [UIFont systemFontOfSize:18];
    _bottomCancel.titleLabel.textColor = [UIColor whiteColor];
    [_bottomCancel addTarget:self action:@selector(bottomCancelClick:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _bottomCancel;
}
- (UIButton *)shotButton{
  if (!_shotButton) {
    _shotButton  = [[UIButton alloc]initWithFrame:CGRectZero];
    _shotButton.backgroundColor  = [[UIColor whiteColor] colorWithAlphaComponent:1];
    _shotButton.layer.cornerRadius = kShotBtnWidth * 0.5;
    _shotButton.layer.borderWidth = 9;
    _shotButton.layer.borderColor = [[UIColor grayColor] colorWithAlphaComponent:0.5].CGColor;
    [_shotButton addTarget:self action:@selector(takePicture) forControlEvents:UIControlEventTouchUpInside];
  }
  return _shotButton;
}

- (UITextField *)licensePlate{
  if (!_licensePlate) {
    _licensePlate = [[UITextField alloc]initWithFrame:CGRectZero];
    _licensePlate.textAlignment = NSTextAlignmentCenter;
    _licensePlate.font = kSystemFontOfSize(16);
    _licensePlate.adjustsFontSizeToFitWidth = YES;
    _licensePlate.textColor = [UIColor whiteColor];
//    _licensePlate.placeholder = @"填写车牌";
    NSDictionary *attrs = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    _licensePlate.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"填写车牌" attributes:attrs];
    _licensePlate.enabled = NO;
    _licensePlate.hidden = YES;
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapChangeLicensePlate:)];
//    [_licensePlate addGestureRecognizer:tap];
//    [self viewBorderLineWithLineWidth:2 lineColor:[UIColor whiteColor] view:_licensePlate];
  }
  return _licensePlate;
}

- (MAMapView *)mapView{
  if (!_mapView) {
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(kScreenWidth - 111 - 30, kSafeStatusBarHeight + 44, 111, 160)];
//    [_mapView setZoomLevel:14 animated:YES];
    //设置mapView的代理
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    _mapView.showsCompass = NO;
    _mapView.showsScale = NO;
    
    for (UIView *view in _mapView.subviews) {
      if ([view isKindOfClass:[UIImageView class]]) {
        [view removeFromSuperview];
      }
    }
  }
  return _mapView;
}

- (UIButton *)rollingButton{
  if (!_rollingButton) {
    _rollingButton = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth - 47 - 12, CGRectGetMaxY(self.mapView.frame) + 20, 47, 40)];
    [_rollingButton setImage:[UIImage imageNamed:@"rollingButton"] forState:UIControlStateNormal];
    [_rollingButton setTitle:@"翻转" forState:UIControlStateNormal];
    _rollingButton.titleLabel.font = kSystemFontOfSize(12);
    _rollingButton.titleLabel.textColor = [UIColor whiteColor];
    [_rollingButton setImageEdgeInsets:UIEdgeInsetsMake(0, 5,8, -_rollingButton.titleLabel.bounds.size.width)];
    [_rollingButton setTitleEdgeInsets:UIEdgeInsetsMake(_rollingButton.imageView.frame.size.height+8 ,-_rollingButton.imageView.frame.size.width, 0,0)];
    [_rollingButton addTarget:self action:@selector(switchCameraClicked:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _rollingButton;
}
- (UIButton *)lightButton{
  if (!_lightButton) {
    _lightButton = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth - 47 - 12,  CGRectGetMaxY(self.rollingButton.frame) + 16, 47, 40)];
    [_lightButton setImage:[UIImage imageNamed:@"lightButtonOff"] forState:UIControlStateNormal];
    [_lightButton setImage:[UIImage imageNamed:@"lightButtonOn"] forState:UIControlStateSelected];
    [_lightButton setTitle:@"闪光灯" forState:UIControlStateNormal];
    _lightButton.titleLabel.font = kSystemFontOfSize(12);
    _lightButton.titleLabel.textColor = [UIColor whiteColor];
    [_lightButton setImageEdgeInsets:UIEdgeInsetsMake(0, 5,8, -_lightButton.titleLabel.bounds.size.width)];
    [_lightButton setTitleEdgeInsets:UIEdgeInsetsMake(_lightButton.imageView.frame.size.height+8 ,-_lightButton.imageView.frame.size.width, 0,0)];
    [_lightButton addTarget:self action:@selector(switchLightClicked:) forControlEvents:UIControlEventTouchUpInside];
    
  }
  return _lightButton;
}
- (UILabel *)timeLabel{
  if (!_timeLabel) {
    _timeLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.font = kBoldSystemFontOfSize(12);
  }
  return _timeLabel;
}
- (UIImageView *)dateIcon{
  if (!_dateIcon) {
    _dateIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"dateIcon"]];
  }
  return _dateIcon;
}
- (UILabel *)dateLabel{
  if (!_dateLabel) {
    _dateLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    _dateLabel.font = kSystemFontOfSize(12);
    _dateLabel.textColor = [UIColor whiteColor];
  }
  return _dateLabel;
}
-(UIImageView *)addressIcon{
  if (!_addressIcon) {
    _addressIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"addressIcon"]];
  }
  return _addressIcon;
}
- (UILabel *)addressLabel{
  if (!_addressLabel) {
    _addressLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    _addressLabel.font = kSystemFontOfSize(12);
    _addressLabel.textColor = [UIColor whiteColor];
  }
  return _addressLabel;
}
- (SLShotFocusView *)focusView {
  if (_focusView == nil) {
    _focusView= [[SLShotFocusView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
  }
  return _focusView;
}
- (UIButton *)mapIconButton{
  if (!_mapIconButton) {
    _mapIconButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_mapIconButton setImage:[UIImage imageNamed:@"mapIcon"] forState:UIControlStateNormal];
    _mapIconButton.tag =102;
    [_mapIconButton addTarget:self action:@selector(hideMapViewWithButton:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _mapIconButton;
}
- (UIButton *)addButton{
  if (!_addButton) {
    _addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addButton setImage:[UIImage imageNamed:@"addbutton"] forState:UIControlStateNormal];
    _addButton.tag = 99;
    [_addButton addTarget:self action:@selector(mapZoomWithbutton:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _addButton;
}
- (UIButton *)reduiceButton{
  if (!_reduiceButton) {
    _reduiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_reduiceButton setImage:[UIImage imageNamed:@"reduceButton"] forState:UIControlStateNormal];
    _reduiceButton.tag = 100;
    [_reduiceButton addTarget:self action:@selector(mapZoomWithbutton:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _reduiceButton;
}
- (UIButton *)closeMapButton{
  if (!_closeMapButton) {
    _closeMapButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_closeMapButton setImage:[UIImage imageNamed:@"closeButton"] forState:UIControlStateNormal];
    _closeMapButton.tag = 101;
    [_closeMapButton addTarget:self action:@selector(hideMapViewWithButton:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _closeMapButton;
}

- (UIImageView *)distanceIcon{
  if (!_distanceIcon) {
    _distanceIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"distanceIcon"]];
  }
  return _distanceIcon;
}
- (UILabel *)distanceLabel{
  if (!_distanceLabel) {
    _distanceLabel = [UILabel new];
    _distanceLabel.font = kSystemFontOfSize(17);
    _distanceLabel.textColor = [UIColor whiteColor];
  }
  return _distanceLabel;
}

//- (WaterCameraQRCodeView *)qrCodeView{
//  if (!_qrCodeView) {
//    _qrCodeView = [[WaterCameraQRCodeView alloc]initWithFrame:CGRectZero];
//  }
//  return _qrCodeView;
//}

- (UIImageView *)photoBackView{
  if (!_photoBackView) {
    _photoBackView = [[UIImageView alloc]initWithFrame:CGRectZero];
    _photoBackView.userInteractionEnabled = YES;
  }
  return _photoBackView;
}
- (UIImageView *)mapSnapView{
  if (!_mapSnapView) {
    _mapSnapView = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth - 141 - 30, kSafeStatusBarHeight + 44, 141, 160)];
  }
  return _mapSnapView;
}
- (void)licensePlateText:(NSString *)lincePlateStr{
  if ([lincePlateStr gj_hasValue]) {
    self.licensePlate.text = lincePlateStr;
    self.licensePlate.hidden = NO;
  }else{
    self.licensePlate.hidden = YES;
  }
  
}
#pragma mark - Setter
- (void)setShootingOrientation:(UIDeviceOrientation)shootingOrientation {
  _shootingOrientation = shootingOrientation;
  [UIView animateWithDuration:0.3 animations:^{
    switch (shootingOrientation) {
      case UIDeviceOrientationPortrait:
        self.rollingButton.transform = CGAffineTransformMakeRotation(0);
        break;
      case UIDeviceOrientationLandscapeLeft:
        self.rollingButton.transform = CGAffineTransformMakeRotation(M_PI/2.0);
        break;
      case UIDeviceOrientationLandscapeRight:
        self.rollingButton.transform = CGAffineTransformMakeRotation(-M_PI/2.0);
        break;
      case UIDeviceOrientationPortraitUpsideDown:
        self.rollingButton.transform = CGAffineTransformMakeRotation(-M_PI);
        break;
      default:
        break;
    }
  }];
}

- (void)setIsShowMap:(BOOL)isShowMap{
  _isShowMap = isShowMap;
  self.mapView.hidden = self.closeMapButton.hidden  = self.reduiceButton.hidden  = self.addButton.hidden  = !_isShowMap;
  self.mapIconButton.hidden = isShowMap;
}
- (void)setIsShowDistance:(BOOL)isShowDistance{
  _isShowDistance = isShowDistance;
  self.distanceLabel.hidden = self.distanceIcon.hidden = !_isShowDistance;
}
#pragma mark - dealloc
- (void)dealloc{
//  [self.videoCamera stopCameraCapture];
//  [GJGCDTimer cancelTask:self.gcdTimerName];
}
- (void)distoaryView{
  [self.videoCamera stopCameraCapture];
  [GJGCDTimer cancelTask:self.gcdTimerName];
}

- (void)drawRect:(CGRect)rect{
  [self viewBorderLineWithLineWidth:2 lineColor:[UIColor whiteColor] view:_licensePlate];
}

@end
